package com.chuang.bootplus.controller.admin.listener.topic;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chuang.bootplus.entity.topic.Topic;
import com.chuang.bootplus.service.TopicService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
public class TMapTReadListener implements ReadListener<Topic> {

    private static final int BATCH_COUNT = 100;
    private List<Topic> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);



    private final TopicService topicService;

    public TMapTReadListener(TopicService topicService) {
        this.topicService=topicService;
    }


    // 批量更新
    private void updateData() {
        cachedDataList.stream().forEach(t->{
            String realId = t.getRealId();
            Topic one = topicService.getOne(new LambdaQueryWrapper<Topic>().eq(Topic::getRealId, realId));
            one.setParentId(t.getParentId());
            one.setValue(t.getValue());
            topicService.updateById(one);
        });
    }

    @Transactional
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("{}条数据，开始更新数据库！", cachedDataList.size());

        updateData();
        log.info("存储数据库成功！");
    }

    @Override
    public void invoke(Topic topic, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(topic));
        cachedDataList.add(topic);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            updateData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

}
